<script setup lang="ts">
import { computed, h, onMounted, ref } from 'vue';
import {
  NButton,
  NCard,
  NDataTable,
  NEmpty,
  NForm,
  NFormItem,
  NInput,
  NList,
  NListItem,
  NModal,
  NPopconfirm,
  NSelect,
  NSpace,
  NTabPane,
  NTabs,
  NTag,
  NThing,
  useMessage
} from 'naive-ui';
import type { DataTableColumns } from 'naive-ui';

// 消息提示
const message = useMessage();

// 角色相关数据
interface Role {
  id: string;
  name: string;
  code: string;
  description: string;
  status: 'active' | 'inactive';
}

// 用户相关数据
interface User {
  id: string;
  username: string;
  email: string;
  role: string;
  status: 'active' | 'inactive';
}

// 菜单相关数据
interface Menu {
  id: string;
  name: string;
  path: string;
  icon: string;
  status: 'active' | 'inactive';
}

// 角色列表
const roles = ref<Role[]>([
  {
    id: '1',
    name: '管理员',
    code: 'admin',
    description: '系统管理员，拥有所有权限',
    status: 'active'
  },
  {
    id: '2',
    name: '普通用户',
    code: 'user',
    description: '普通用户，拥有基本权限',
    status: 'active'
  },
  {
    id: '3',
    name: '访客',
    code: 'guest',
    description: '访客用户，只读权限',
    status: 'inactive'
  },
  {
    id: '4',
    name: '财务专员',
    code: 'finance',
    description: '财务部门专用角色',
    status: 'active'
  },
  {
    id: '5',
    name: '人事专员',
    code: 'hr',
    description: '人事部门专用角色',
    status: 'active'
  }
]);

// 用户列表
const users = ref<User[]>([
  {
    id: '1',
    username: 'admin',
    email: 'admin@example.com',
    role: 'admin',
    status: 'active'
  },
  {
    id: '2',
    username: 'user1',
    email: 'user1@example.com',
    role: 'user',
    status: 'active'
  },
  {
    id: '3',
    username: 'user2',
    email: 'user2@example.com',
    role: 'user',
    status: 'inactive'
  },
  {
    id: '4',
    username: 'finance1',
    email: 'finance1@example.com',
    role: 'finance',
    status: 'active'
  },
  {
    id: '5',
    username: 'hr1',
    email: 'hr1@example.com',
    role: 'hr',
    status: 'active'
  }
]);

// 菜单列表
const menus = ref<Menu[]>([
  {
    id: '1',
    name: '首页',
    path: '/dashboard',
    icon: 'home',
    status: 'active'
  },
  {
    id: '2',
    name: '系统管理',
    path: '/system',
    icon: 'setting',
    status: 'active'
  },
  {
    id: '3',
    name: '用户管理',
    path: '/system/users',
    icon: 'user',
    status: 'active'
  },
  {
    id: '4',
    name: '角色管理',
    path: '/system/roles',
    icon: 'team',
    status: 'active'
  },
  {
    id: '5',
    name: '菜单管理',
    path: '/system/menus',
    icon: 'menu',
    status: 'active'
  },
  {
    id: '6',
    name: '权限管理',
    path: '/system/permission',
    icon: 'lock',
    status: 'active'
  }
]);

// 当前选中的角色
const selectedRole = ref<Role | null>(null);

// 搜索关键词
const searchKeyword = ref('');

// 模态框相关
const showModal = ref(false);
const modalType = ref<'user' | 'menu'>('user'); // user表示用户，menu表示菜单
const selectedUserId = ref<string | null>(null);
const selectedMenuId = ref<string | null>(null);

// 过滤后的角色列表
const filteredRoles = computed(() => {
  if (!searchKeyword.value) {
    return roles.value;
  }
  return roles.value.filter(
    role =>
      role.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      role.code.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
});

// 当前选中角色的用户列表
const roleUsers = computed(() => {
  if (!selectedRole.value) return [];
  return users.value.filter(user => user.role === selectedRole.value?.code);
});

// 可添加到角色的用户列表（不属于当前角色的用户）
const availableUsers = computed(() => {
  if (!selectedRole.value) return [];
  return users.value.filter(user => user.role !== selectedRole.value?.code);
});

// 当前选中角色的菜单列表
const roleMenus = computed(() => {
  if (!selectedRole.value) return [];
  // 这里应该根据实际权限关系过滤菜单
  // 暂时返回所有菜单作为示例
  return menus.value;
});

// 可添加到角色的菜单列表
const availableMenus = computed(() => {
  if (!selectedRole.value) return [];
  // 这里应该根据实际业务逻辑过滤
  // 暂时返回所有菜单作为示例
  return menus.value;
});

// 从角色中移除用户
const removeUserFromRole = (user: User) => {
  // 实际项目中这里应该调用API更新用户角色
  message.success(`已将用户 ${user.username} 从角色中移除`);
};

// 从角色中移除菜单
const removeMenuFromRole = (menu: Menu) => {
  // 实际项目中这里应该调用API更新角色菜单权限
  message.success(`已将菜单 ${menu.name} 从角色中移除`);
};

// 表格列定义 - 用户
const userColumns: DataTableColumns<User> = [
  {
    title: '用户名',
    key: 'username'
  },
  {
    title: '邮箱',
    key: 'email'
  },
  {
    title: '状态',
    key: 'status',
    render(row) {
      return h(
        NTag,
        { type: row.status === 'active' ? 'success' : 'error' },
        { default: () => (row.status === 'active' ? '激活' : '禁用') }
      );
    }
  },
  {
    title: '操作',
    key: 'actions',
    render(row) {
      return h(
        NPopconfirm,
        {
          onPositiveClick: () => removeUserFromRole(row)
        },
        {
          default: () => '确定要将该用户从角色中移除吗？',
          trigger: () =>
            h(
              NButton,
              {
                size: 'small',
                type: 'error',
                quaternary: true
              },
              { default: () => '移除' }
            )
        }
      );
    }
  }
];

// 表格列定义 - 菜单
const menuColumns: DataTableColumns<Menu> = [
  {
    title: '菜单名称',
    key: 'name'
  },
  {
    title: '路径',
    key: 'path'
  },
  {
    title: '状态',
    key: 'status',
    render(row) {
      return h(
        NTag,
        { type: row.status === 'active' ? 'success' : 'error' },
        { default: () => (row.status === 'active' ? '激活' : '禁用') }
      );
    }
  },
  {
    title: '操作',
    key: 'actions',
    render(row) {
      return h(
        NPopconfirm,
        {
          onPositiveClick: () => removeMenuFromRole(row)
        },
        {
          default: () => '确定要将该菜单从角色中移除吗？',
          trigger: () =>
            h(
              NButton,
              {
                size: 'small',
                type: 'error',
                quaternary: true
              },
              { default: () => '移除' }
            )
        }
      );
    }
  }
];

// 选择角色
const selectRole = (role: Role) => {
  selectedRole.value = role;
};

// 获取状态标签
const getStatusTag = (status: 'active' | 'inactive') => {
  return h(
    NTag,
    { type: status === 'active' ? 'success' : 'error', size: 'small' },
    { default: () => (status === 'active' ? '激活' : '禁用') }
  );
};

// 打开添加用户模态框
const openAddUserModal = () => {
  if (!selectedRole.value) {
    message.warning('请先选择一个角色');
    return;
  }
  modalType.value = 'user';
  selectedUserId.value = null;
  showModal.value = true;
};

// 打开添加菜单模态框
const openAddMenuModal = () => {
  if (!selectedRole.value) {
    message.warning('请先选择一个角色');
    return;
  }
  modalType.value = 'menu';
  selectedMenuId.value = null;
  showModal.value = true;
};

// 添加用户到角色
const addUserToRole = () => {
  if (!selectedUserId.value) {
    message.warning('请选择一个用户');
    return;
  }

  const selectedUser = users.value.find(user => user.id === selectedUserId.value);
  if (!selectedUser) {
    message.error('用户不存在');
    return;
  }

  // 实际项目中这里应该调用API更新用户角色
  message.success(`已将用户 ${selectedUser.username} 添加到角色中`);
  showModal.value = false;
};

// 添加菜单到角色
const addMenuToRole = () => {
  if (!selectedMenuId.value) {
    message.warning('请选择一个菜单');
    return;
  }

  const selectedMenu = menus.value.find(menu => menu.id === selectedMenuId.value);
  if (!selectedMenu) {
    message.error('菜单不存在');
    return;
  }

  // 实际项目中这里应该调用API更新角色菜单权限
  message.success(`已将菜单 ${selectedMenu.name} 添加到角色中`);
  showModal.value = false;
};

// 组件挂载时默认选择第一个角色
onMounted(() => {
  if (roles.value.length > 0) {
    selectedRole.value = roles.value[0];
  }
});
</script>

<template>
  <div class="permission-management">
    <NCard title="权限管理">
      <div class="container">
        <!-- 左侧角色列表 -->
        <div class="role-list">
          <div class="search-box">
            <NInput v-model:value="searchKeyword" placeholder="搜索角色名称或编码" clearable />
          </div>

          <NList class="role-list">
            <NListItem
              v-for="role in filteredRoles"
              :key="role.id"
              :class="{ active: selectedRole?.id === role.id }"
              @click="selectRole(role)"
            >
              <NThing>
                <template #header>
                  <span class="role-name">{{ role.name }}</span>
                </template>
                <template #description>
                  <span class="role-code">{{ role.code }}</span>
                </template>
                <template #header-extra>
                  <component :is="getStatusTag(role.status)" />
                </template>
                <div v-if="role.description" class="role-description">
                  {{ role.description }}
                </div>
              </NThing>
            </NListItem>

            <NEmpty v-if="filteredRoles.length === 0" description="暂无匹配角色" />
          </NList>
        </div>

        <!-- 右侧详情区域 -->
        <div v-if="selectedRole" class="detail-area">
          <div class="role-info">
            <h3>当前角色: {{ selectedRole.name }}</h3>
            <p class="role-description">{{ selectedRole.description }}</p>
          </div>

          <NTabs type="line" animated>
            <NTabPane name="users" tab="用户">
              <div class="tab-content">
                <div class="toolbar">
                  <NButton type="primary" @click="openAddUserModal">添加用户</NButton>
                </div>
                <NDataTable
                  v-if="roleUsers.length > 0"
                  :columns="userColumns"
                  :data="roleUsers"
                  :pagination="{ pageSize: 5 }"
                />
                <NEmpty v-else description="该角色下暂无用户">
                  <template #extra>
                    <NButton type="primary" @click="openAddUserModal">添加用户</NButton>
                  </template>
                </NEmpty>
              </div>
            </NTabPane>
            <NTabPane name="menus" tab="菜单">
              <div class="tab-content">
                <div class="toolbar">
                  <NButton type="primary" @click="openAddMenuModal">添加菜单</NButton>
                </div>
                <NDataTable
                  v-if="roleMenus.length > 0"
                  :columns="menuColumns"
                  :data="roleMenus"
                  :pagination="{ pageSize: 5 }"
                />
                <NEmpty v-else description="暂无菜单数据">
                  <template #extra>
                    <NButton type="primary" @click="openAddMenuModal">添加菜单</NButton>
                  </template>
                </NEmpty>
              </div>
            </NTabPane>
          </NTabs>
        </div>

        <!-- 未选择角色时的提示 -->
        <div v-else class="detail-area placeholder">
          <NEmpty description="请从左侧选择一个角色">
            <template #extra>
              <NButton v-if="roles.length > 0" @click="selectedRole = roles[0]">选择第一个角色</NButton>
            </template>
          </NEmpty>
        </div>
      </div>
    </NCard>

    <!-- 添加用户/菜单模态框 -->
    <NModal
      v-model:show="showModal"
      preset="card"
      class="add-modal"
      :title="modalType === 'user' ? '添加用户' : '添加菜单'"
    >
      <NForm>
        <!-- 添加用户表单 -->
        <NFormItem v-if="modalType === 'user'" label="选择用户">
          <NSelect
            v-model:value="selectedUserId"
            :options="availableUsers.map(user => ({ label: user.username, value: user.id }))"
            placeholder="请选择用户"
          />
        </NFormItem>

        <!-- 添加菜单表单 -->
        <NFormItem v-if="modalType === 'menu'" label="选择菜单">
          <NSelect
            v-model:value="selectedMenuId"
            :options="availableMenus.map(menu => ({ label: menu.name, value: menu.id }))"
            placeholder="请选择菜单"
          />
        </NFormItem>
      </NForm>

      <template #footer>
        <NSpace justify="end">
          <NButton @click="showModal = false">取消</NButton>
          <NButton
            type="primary"
            :disabled="(modalType === 'user' && !selectedUserId) || (modalType === 'menu' && !selectedMenuId)"
            @click="modalType === 'user' ? addUserToRole() : addMenuToRole()"
          >
            确定
          </NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<style scoped>
.permission-management {
  padding: 16px;
}

.add-modal {
  width: 90%;
  max-width: 500px;
}

.container {
  display: flex;
  gap: 16px;
  height: calc(100vh - 180px);
}

.role-list {
  width: 300px;
  border-right: 1px solid var(--n-border-color);
  padding-right: 16px;
  overflow-y: auto;
}

.search-box {
  position: sticky;
  top: 0;
  background: white;
  padding: 8px 0;
  z-index: 10;
}

.role-name {
  font-weight: bold;
  font-size: 16px;
}

.role-code {
  font-size: 12px;
  color: #999;
}

.role-description {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.n-list-item {
  cursor: pointer;
  border-radius: 4px;
  margin-bottom: 8px;
}

.n-list-item:hover {
  background-color: #f5f5f5;
}

.n-list-item.active {
  background-color: #e6f4ff;
  border: 1px solid #1890ff;
}

.detail-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.detail-area.placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
}

.role-info {
  padding: 16px 0;
  border-bottom: 1px solid var(--n-border-color);
}

.role-info h3 {
  margin: 0 0 8px 0;
}

.role-info .role-description {
  margin: 0;
  color: #666;
}

.role-list {
  background-color: transparent;
  margin-top: 16px;
}

.tab-content {
  padding: 16px 0;
  flex: 1;
}

.toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .container {
    flex-direction: column;
    height: auto;
  }

  .role-list {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid var(--n-border-color);
    padding-right: 0;
    padding-bottom: 16px;
  }

  .permission-management {
    padding: 8px;
  }

  :deep(.n-data-table) {
    font-size: 12px;
  }

  :deep(.n-data-table th) {
    font-size: 12px;
    padding: 8px;
  }

  :deep(.n-data-table td) {
    font-size: 12px;
    padding: 8px;
  }
}
</style>
